package com.hundsun.yr.universal.p2p.utils;

import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Matrix;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;

import java.util.Hashtable;

/**
 * Created by linc on 2017/5/19.
 */
public class QRCodeUtil {

    private static final int BLACK = 0xff000000;

    public static Bitmap createQRCode(String str, int widthAndHeight) {
        try {
            // 判断URL合法性
            if (str == null || "".equals(str) || str.length() < 1) {
                return null;
            }
            Hashtable hints = new Hashtable();
            hints.put(EncodeHintType.CHARACTER_SET, "utf-8");

            hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
            // 图像数据转换，使用了矩阵转换
            BitMatrix matrix = new MultiFormatWriter().encode(str, BarcodeFormat.QR_CODE, widthAndHeight, widthAndHeight, hints);
            int width = matrix.getWidth();
            int height = matrix.getHeight();
            int[] pixels = new int[width * height];
            // 下面这里按照二维码的算法，逐个生成二维码的图片，
            // 两个for循环是图片横列扫描的结果
            for (int y = 0; y < height; y++) {
                for (int x = 0; x < width; x++) {
                    if (matrix.get(x, y)) {
                        pixels[y * width + x] = BLACK;
                    }
                }
            }
    // 生成二维码图片的格式，使用ARGB_8888
    Bitmap bitmap = Bitmap.createBitmap(width, height,
            Bitmap.Config.ARGB_8888);
    bitmap.setPixels(pixels, 0, width, 0, 0, width, height);
        return bitmap;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    public static Bitmap createQrCodeLogo(String content, int widthAndHeight, Bitmap logo) {
        Bitmap qrCode = createQRCode(content, widthAndHeight);
        // 创建一个画布
        Canvas canvas = new Canvas(qrCode);
        // 计算logo的宽高
        int logoHeight = qrCode.getHeight() / 6;
        // Matrix 矩阵变换  3 x 3
        Matrix matrix = new Matrix();
        float scale = (float) logoHeight / logo.getHeight();
        // 设置缩放比例
        matrix.setScale(scale, scale);
        // 生成目标大小的logo
        Bitmap scaleLogo = Bitmap.createBitmap(logo, 0, 0, logo.getWidth(), logo.getHeight(), matrix, true);
        // 将logo画到画布上
        canvas.drawBitmap(scaleLogo, logoHeight * 2.5f, logoHeight * 2.5f, null);
        // 保存
        canvas.save();
        canvas.restore();
        return qrCode;
    }
}
